<?php

require_once PATH_FFWD.'prototypes/form.base.php';

class AjaxForm extends BaseForm{/* extends Baserecord ?! :)  */
	public $prikey='';
	public $e=NULL;
	public $fields=Array();
	public $action=NULL;
	public $method='POST';
	public $uid='';
	public $formdata=Array();
	public $settings=Array(
		'class'=>'ajaxform',
	);
	
	public function __construct($e,$action=NULL){
		$this->action=$action;
		$this->uid=uniqid();
		
		if(isset($_GET['formdata'])){
			$this->formdata=json_decode($_GET['formdata'],1,100);			
		}
		if($e){
			if(is_array($e)){
				foreach($e as $k=>$v)$this->fields[$k]=$v;
			}else{
				$this->e=&$e;
				$this->fields=&$e->fields;
			};
		};
	}
	
	public function __destruct(){
	
	}
	
	
	
	
	public function renderOpen($p=Array()){
		if(!isset($p['class']))$p['class']='ajaxform';else $p['class'].=' ajaxform';
		echo "<form class='".$p['class']."' id='".$this->uid."' ".
				 " action='".$this->action."' method='".$this->method."'>";
		echo html_input_hidden(Array(
			'name'=>'__sender','value'=>$_SERVER['REQUEST_URI'],
		));
	}
	
	public function renderClose($p=Array()){
		echo "</form>";	
	}
	
	
	public function render($p=Array()){
		$this->renderOpen($p);
		foreach(array_keys($this->fields) as $fldname)
			$this->renderInput($fldname);
		$this->renderClose($p);
	}
	
	public function renderSubmit($p=Array()){
		if(!isset($p['value']))$p['value']='submit';
		$p['onclick']='document.getElementById("'.$this->uid.'").submit()';
		echo html_input_button($p);	
	}
	
	public function __get($name){
		$this->renderInput($name);
	}
	

	public function renderInput($name,$p=Array()){
		if(!isset($this->fields[$name]))return;	
		if(!isset($p['placeholder']))$p['placeholder']=t($name);	
		$p['formuid']=$this->uid;
		$p['name']=$this->fields[$name]->getPointer();
		$fldname=$this->fields[$name]->name;		
		if(isset($this->formdata[$fldname])){
			$p['value']=$this->formdata[$fldname];
		}
		echo $this->fields[$name]->input($p);
	}	
	
}